package com.wolfman.socket.server.mapper.impl;

import com.wolfman.socket.server.mapper.PersonMapper;
import com.wolfman.socket.server.pojo.Person;
import com.wolfman.socket.server.util.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @Title
 * @Description
 * @Author WolfMan
 * @Date 2022/11/26 16:08
 * @Email 2370032534@qq.com
 */
public class PersonMapperImpl implements PersonMapper {

    @Override
    public Object saverPerson(Person person) throws Exception {
        PreparedStatement statement = null;
        try {
            Connection connection = JDBCUtils.getConnection();
            String sql = "insert into person(age,name) values(?,?)";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, person.getAge());
            statement.setString(2, person.getName());
            statement.execute();
        } catch (Exception e) {
            throw e;
        } finally {
            JDBCUtils.close();
            JDBCUtils.close(statement);
        }
        return true;
    }

    @Override
    public Object selectPersonById(Integer id) {
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement statement = null;
        ResultSet result = null;
        try {
            String sql = "select * from person where id = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, id);
            result = statement.executeQuery();
            if (result.next()) {
                return new Person(result.getInt("id"), result.getInt("age"), result.getString("name"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close();
            JDBCUtils.close(statement, result);
        }
        return null;
    }
}
